package com.company.beauty.feign.config;

import cn.hutool.core.lang.Dict;
import com.company.nuwa.common.constants.Headers;
import com.company.nuwa.common.utils.JsonUtils;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;
import java.util.Objects;

/**
 * <p>Feign配置</p>
 *
 * @author lili
 * @version 1.0: FeignConfiguration
 * @date 2023/10/16 16:57
 */
@Slf4j
@Configuration
public class FeignConfiguration implements RequestInterceptor {

    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(attributes)) {
            log.warn("FeignConfiguration attributes is null {}", requestTemplate.headers());
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        if (Objects.isNull(request)) {
            log.warn("FeignConfiguration request is null {}", requestTemplate.headers());
            return;
        }
        Enumeration<String> headerNames = request.getHeaderNames();
        if (Objects.isNull(headerNames)) {
            log.warn("FeignConfiguration headerNames is null {}", requestTemplate.headers());
            return;
        }

        Dict params = Dict.create();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String value = request.getHeader(name);
            if (include(name)) {
                requestTemplate.header(name, value);
            }
            params.put(name, value);
        }
        log.info("headers: {}", JsonUtils.objectToJson(params));
    }

    private boolean include(String headerName) {
        return StringUtils.equals(Headers.PLATFORM_ID, headerName)
                || StringUtils.equals(Headers.PLATFORM_SECRET, headerName)
                || StringUtils.equals(Headers.TRACE_ID, headerName)
                || StringUtils.equals(Headers.X_ACCESS_TOKEN, headerName);
    }

}
